package com.example.wanandroid_copy2.ui.system.view

import android.content.Intent
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.example.wanandroid_copy2.R
import com.example.wanandroid_copy2.ui.article.view.ArticleFragment
import com.example.wanandroid_copy2.ui.system.viewmodel.SystemViewModel
import com.kkaka.wanandroid.system.data.SecondMenuRsp
import com.kkaka.wanandroid.system.data.TopMenu
import com.kkaka.wanandroid.system.data.TopMenuRsp
import kotlinx.android.synthetic.main.fragment_article.*

class SystemFragment : ArticleFragment<SystemViewModel>() {

    lateinit var mAdapter : SystemMenuAdapter

    override fun initData() {
        super.initData()
        mViewModel.getTopMenu()
    }

    override fun initView() {
        super.initView()

        mRvArticle.layoutManager = GridLayoutManager(activity, 4)
        mAdapter = SystemMenuAdapter(R.layout.item_system_top_menu_content,R.layout.item_system_top_menu_head,null)
        mRvArticle.adapter = mAdapter
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            var item = mAdapter.getItem(position) as TopMenu
            toPage(item)
        }
        //无加载更多
        mAdapter.setEnableLoadMore(false)
    }

    private fun toPage(item: TopMenu) {
        val data = item.childrens
        val topTitles = item.header
        val ids = arrayListOf<Int>()
        var titles = arrayListOf<String>()
        data.forEach {
            ids.add(it.id)
            titles.add(it.name)
        }
        // 跳转到SystemArticleActivity
        startActivity(Intent(context, SystemArticleActivity::class.java).apply {
            putIntegerArrayListExtra("ids", ids)
            putStringArrayListExtra("titles", titles)
            putExtra("topTitles", topTitles)
        })
    }

    override fun onRefreshData() {
        mViewModel.getTopMenu()
    }

    override fun onLoadMore() {
    }

    override fun dataObserver() {
        mViewModel.topMenuLiveData.observe(this, Observer {
            buildTopMenu(it?.data)
        })
    }

    private fun buildTopMenu(data: List<TopMenuRsp>?) {
        val list = arrayListOf<TopMenu>()
        data?.forEach {
            list.add(TopMenu(true, it.name, !it.children.isEmpty(), it.children))
            it.children.forEach {
                list.add(TopMenu(SecondMenuRsp(it.name, it.id)))
            }
        }
        if(msrlRefresh.isRefreshing){
            msrlRefresh.isRefreshing = false
        }
        mAdapter.setNewData(list)
    }
}